# coding = utf-8

'''
对HDenseUNET做一些分析工作
'''

from network.HDenseUnet import dense_rnn_net
from dataset.IRCAD_HDENSE_UNET import IRCAD_DATA
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler
import torch
from tqdm import tqdm
import numpy as np
import json
import os
from scipy import ndimage
from torch.nn.functional import softmax
from skimage import measure
from pathlib2 import Path

def analysis():
    roi_path = "/home/diaozhaoshuo/log/BeliefFunctionNN/3diradb_chengkung/output"

    for j in [2,6,14,16,19]:
        data_path = "/datasets/3Dircadb/origion/case_{}".format(str(j).zfill(5))
        origion_data_path = os.path.join(data_path, "image.npy")
        mask_path = os.path.join(data_path, "segment.npy")
        image = np.load(origion_data_path)
        mask = np.load(mask_path)

        roi_file = os.path.join(roi_path, "predict_{}.npy".format(str(j).zfill(5)))
        roi = np.load(roi_file)

        image = image.transpose([1, 2, 0])
        mask = mask.transpose([1, 2, 0])
        roi = roi.transpose([1, 2, 0])
        print(np.unique(mask))

        score_path = "/home/diaozhaoshuo/log/BeliefFunctionNN/hdenseunet/predict/case_{}".format(str(j).zfill(5))
        score1_file = os.path.join(score_path, "score1.npy")
        score2_file = os.path.join(score_path, "score2.npy")
        score1 = np.load(score1_file)
        score2 = np.load(score2_file)

        label = mask.copy()
        label[label==1] = 0
        label[label==2] = 1


        score0 = 1 - (score1+score2)
        p1 = np.zeros(score0.shape)
        p2 = np.zeros(score0.shape)
        p1[score2>score1] = 1
        p2[score2>score0] = 1
        p = p1+p2
        p[p<2] =0
        p[p==2] =1


        score1[score1>=0.5] = 1
        score1[score1<0.5] = 0
        score2[score2>=0.9] = 1
        score2[score2<0.9] = 0
        score1[score2==1] = 1



        dice = 2 * (p*label).sum() / (p.sum() + label.sum())
        print(j,dice)

        Segmask = p
        box = []
        [liver_res, num] = measure.label(roi, return_num=True)
        region = measure.regionprops(liver_res)
        for i in range(num):
            box.append(region[i].area)
        label_num = box.index(max(box)) + 1
        liver_res[liver_res != label_num] = 0
        liver_res[liver_res == label_num] = 1

        #  preserve the largest liver
        roi = ndimage.binary_dilation(roi, iterations=1).astype(roi.dtype)
        box = []
        [liver_labels, num] = measure.label(roi, return_num=True)
        region = measure.regionprops(liver_labels)
        for i in range(num):
            box.append(region[i].area)
        label_num = box.index(max(box)) + 1
        liver_labels[liver_labels != label_num] = 0
        liver_labels[liver_labels == label_num] = 1
        liver_labels = ndimage.binary_fill_holes(liver_labels).astype(int)

        #  preserve tumor within ' largest liver' only
        Segmask = Segmask * liver_labels
        Segmask = ndimage.binary_fill_holes(Segmask).astype(int)
        Segmask = np.array(Segmask, dtype='uint8')
        liver_res = np.array(liver_res, dtype='uint8')
        liver_res = ndimage.binary_fill_holes(liver_res).astype(int)
        liver_res[Segmask == 1] = 2
        liver_res = np.array(liver_res, dtype='uint8')

        dice = 2 * (Segmask * label).sum() / (Segmask.sum() + label.sum())
        print(j,dice)

    print()




        #break










if __name__ == '__main__':
    analysis()